package trilium

import (
	"context"
	"gopkg.in/ini.v1"
	"os"
	"strconv"
)

func (cls *Trilium) ApplyConfig(_ context.Context) error {
	cls.LockConfig()
	defer cls.UnlockConfig()

	if err := os.MkdirAll(dataDir, 0755); nil != err {
		return err
	}

	main, err := os.OpenFile(configFilePath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
	if nil != err {
		return err
	}

	defer func() {
		_ = main.Close()
	}()

	var config = cls.GetConfig()

	var content = ini.Empty()

	general, err := content.NewSection("General")
	if nil != err {
		return err
	}

	_, _ = general.NewKey("instanceName", "")
	_, _ = general.NewKey("noAuthentication", "false")
	_, _ = general.NewKey("noBackup", "false")

	network, err := content.NewSection("Network")
	if nil != err {
		return err
	}

	_, _ = network.NewKey("host", config.Listen)
	_, _ = network.NewKey("port", strconv.Itoa(config.Port))
	_, _ = network.NewKey("trustedReverseProxy", "false")

	// 保存
	if err := content.SaveTo(configFilePath); nil != err {
		return err
	}

	return nil
}
